import store from "@/store"
import app from '@/common/config/app.js'
import router, {
	getRouteUrl
} from "@/common/utils/router.js";
import dialog from "@/common/utils/dialog.js";

export function isInWhiteList(url) {
	url = url[0] === '.' ? url.slice(1) : url
	return app.whiteList.some(item => {
		return item.indexOf(url) !== -1
	})
}

export default function permisson() {
	const page = getCurrentPages()[getCurrentPages().length - 1];
	const url = page.route;

	if (!store.state.userType && url.indexOf('pages/account/user-type-select') === -1) {
		router.reLaunch('/pages/account/user-type-select')
		return
	}

	if (!isInWhiteList(url) &&
		!store.state.token &&
		store.state.userType
	) {
		/* 无访问权限，去登录 */
		router.switchTab('/pages/index/index')
		// router.go(1)
		// uni.$emit('login')
	}
}


function isNeedLogin(url) {
	url = url || getRouteUrl();
	if (!isInWhiteList(url) &&
		!store.state.token &&
		store.state.userType &&
		url.indexOf('pages/account/login') === -1
	) {
		return true
	}
	return false
}
// 路由拦截
export function routerInterceptor() {
	uni.addInterceptor('navigateTo', {
		invoke(e) {
			const path = e.url.split('?')[0]
			console.log('path', path);
			if (isNeedLogin(path)) {
				dialog.confirm({
					content: '登录后才可体验完整功能，是否登录',
					cancelText: '暂不登录',
					confirmText: '立即登录',
				}).then(() => {
					router.replace('/pages/account/login')
				})
				console.log('e.url', e.url);
				return Promise.reject('请先登录')
			}
		}
	})
}


export function interceptor() {
	// 路由拦截
	routerInterceptor()
}